//
//  MessgaeHomePageViewController.m
//  ERP
//
//  Created by QA on 16/4/1.
//  Copyright © 2016年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MessgaeHomePageViewController.h"
#import "OAContactPersonDetailViewController.h"

#import "MainAddressBookViewCell.h"
#import "UITableView+Custom.h"
#import "AddressBookEntity.h"
#import "GETimeDifference.h"

#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"

@interface MessgaeHomePageViewController ()<SWTableViewCellDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic,strong) IBOutlet UITableView *tableView;

@property (strong, nonatomic) NSMutableArray *resultArray;
@property (assign, nonatomic) NSInteger segmentActionState;

@end

@implementation MessgaeHomePageViewController
@synthesize tableView = _tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"我的消息"];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.resultArray = [NSMutableArray array];
    self.tableView.tableFooterView= [[UIView alloc] init];
    
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self headerRereshing];
}

- (void)dealloc
{
    NSLog(@"MJTableViewController--dealloc---");
}

#pragma mark 初始化数据处理

- (NSArray *)rightButtons
{
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    [rightUtilityButtons sw_addUtilityButtonWithColor:
     [UIColor colorWithRed:244/255.00 green:86/255.00 blue:78/255.00 alpha:1.0f] title:@"删除"];
    
    return rightUtilityButtons;
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"createUserId = %@",[userInfo.Id MD5]];
    //NSSortDescriptor * updateTimeSort = [[NSSortDescriptor alloc] initWithKey:@"callTime" ascending:NO];
    //NSArray * sortDescriptors = [NSArray arrayWithObjects:updateTimeSort, nil];
    
    NSArray *historyPhoneArray = [AddressBookEntity MR_findAllSortedBy:@"callTime" ascending:NO withPredicate:predicate];
    //NSArray *historyPhoneArray = [AddressBookEntity MR_findAllPredicate:predicate sortedDescriptors:sortDescriptors];
    self.resultArray = [NSMutableArray arrayWithArray:historyPhoneArray];
    [self.tableView reloadData];
    
    //显示提示信息
    if(self.resultArray.count<=0){
        [self.tableView setTableViewNotDataDrawText:@"暂无消息" isShow:YES offset:0];
        self.tableView.backgroundColor = [UIColor whiteColor];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        self.tableView.backgroundColor = ThemeColorBackgroundGary;
    }
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 30;
//}
//
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
//    view.backgroundColor = [UIColor whiteColor];
//    
//    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, 310, 29.5)];
//    lable.textColor = ThemeColorBlue;
//    lable.font = [UIFont boldSystemFontOfSize:15];
//    lable.text = @"全部通话";
//    [view addSubview:lable];
//    
//    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29.5, SuperWidth, 0.5)];
//    lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
//    [view addSubview:lineView];
//    
//    return view;
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.resultArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"MainAddressBookViewCell";
    MainAddressBookViewCell *cell = (MainAddressBookViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[MainAddressBookViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        [cell setRightUtilityButtons:[self rightButtons] WithButtonWidth:68.0f];
        cell.delegate = self;
    }
    
    cell.accessoryBtn.tag = indexPath.row;
    [cell.accessoryBtn addTarget:self action:@selector(accessorySelector:) forControlEvents:UIControlEventTouchUpInside];
    
    AddressBookEntity *model = [self.resultArray objectAtIndex:indexPath.row];
    cell.nameLabel.text = model.userName;
    cell.postLabel.text = model.postName;
    cell.phoneLabel.text = model.mobileNumber;
    cell.bigTimeLabel.text = [GETimeDifference compareCurrentChangeTime:model.callTime];
    cell.timeLabel.text = [GETimeDifference compareCurrentNewTime:model.callTime];
    
    return cell;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 68;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    AddressBookEntity *model = [self.resultArray objectAtIndex:indexPath.row];
    [self callAction:model indexPath:indexPath];
}


#pragma mark - SWTableViewDelegate

- (void)swipeableTableViewCell:(SWTableViewCell *)cell scrollingToState:(SWCellState)state
{
    switch (state) {
        case 0:
            NSLog(@"utility buttons closed");
            break;
        case 1:
            NSLog(@"left utility buttons open");
            break;
        case 2:
            NSLog(@"right utility buttons open");
            break;
        default:
            break;
    }
}

- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerLeftUtilityButtonWithIndex:(NSInteger)index
{
    switch (index) {
        case 0:
            NSLog(@"left button 0 was pressed");
            break;
        case 1:
            NSLog(@"left button 1 was pressed");
            break;
        case 2:
            NSLog(@"left button 2 was pressed");
            break;
        case 3:
            NSLog(@"left btton 3 was pressed");
        default:
            break;
    }
}

- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index
{
    switch (index) {
        case 0:
        {
            NSIndexPath *cellIndexPath = [self.tableView indexPathForCell:cell];
            
            //数据库删除
            AddressBookEntity *tmp = [self.resultArray objectAtIndex:cellIndexPath.row];
            [tmp MR_deleteEntity];
            [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
            
            // Delete button was pressed
            [self.resultArray removeObjectAtIndex:cellIndexPath.row];
            [self.tableView deleteRowsAtIndexPaths:@[cellIndexPath] withRowAnimation:UITableViewRowAnimationLeft];
            
            //设置桌面图标
            NSInteger badgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber;
            [UIApplication sharedApplication].applicationIconBadgeNumber = badgeNumber - 1;
            
            //显示提示信息
            if(self.resultArray.count<=0){
                [self.tableView setTableViewNotDataDrawText:@"暂无消息" isShow:YES offset:30];
                self.tableView.backgroundColor = [UIColor whiteColor];
            } else {
                [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
                self.tableView.backgroundColor = ThemeColorBackgroundGary;
            }
            
            break;
        }
        default:
            break;
    }
}

- (BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell
{
    // allow just one cell's utility button to be open at once
    return YES;
}

- (BOOL)swipeableTableViewCell:(SWTableViewCell *)cell canSwipeToState:(SWCellState)state
{
    switch (state) {
        case 1:
            // set to NO to disable all left utility buttons appearing
            return YES;
            break;
        default:
            break;
    }
    
    return YES;
}

#pragma mark
#pragma mark - Button Event

- (void)accessorySelector:(UIButton*)sender
{
    AddressBookEntity *model = [self.resultArray objectAtIndex:sender.tag];
    OAContactPersonDetailViewController *viewController = [[OAContactPersonDetailViewController alloc] initWithValue:model];
    [self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - 拨打电话
- (void)callAction:(AddressBookEntity *)temp indexPath:(NSIndexPath *)indexPath
{
    NSString *phoneNumber = temp.mobileNumber;
    if (!(phoneNumber && ![phoneNumber isEqualToString:@""])) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"未找到联系电话" delegate:self
                                            cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
        return;
    } else {
        phoneNumber = [NSString stringWithFormat:@"tel://%@",phoneNumber];
    }
    
    //更新拨打电话记录
    [self updateUserCallPhoneNumber:temp];
    NSArray *indexPathOld = @[indexPath];
    [self.tableView reloadRowsAtIndexPaths:indexPathOld withRowAnimation:UITableViewRowAnimationNone];
    
    [self.resultArray removeObject:temp];
    [self.resultArray insertObject:temp atIndex:0];
    NSIndexPath *indexPathNew = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView moveRowAtIndexPath:indexPath toIndexPath:indexPathNew];
    
    //拨打电话(合法拨打电话方式)
    UIWebView *callWebview = [[UIWebView alloc] init];
    NSURL *telURL =[NSURL URLWithString:phoneNumber];
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    [self.view addSubview:callWebview];
}

#pragma mark
#pragma mark - 更新拨打联系人

- (void)updateUserCallPhoneNumber:(AddressBookEntity *)temp
{
    //更新联系人数据
    NSArray *students = [AddressBookEntity MR_findByAttribute:@"identifyID" withValue:temp.identifyID];
    AddressBookEntity *entity = [students firstObject];
    entity.callTime = [NSDate date];
    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
}

@end
